ποΈGitΠ―ΡΠ°ποΈ
.github/agents/speckit.optimize.run.agent.md 911a58089da5fafbf8c7d9f55bc84e98dd2f3cef (911a5808) Text, 21.48 KB
---
description: Audit and optimize governance documents for AI context efficiency.
handoffs:
Tff7b72- label: Amend constitution
agent: speckit.constitution
prompt: Apply the approved optimization changes to the constitution
Tff7b72- label: Verify consistency
agent: speckit.analyze
Tc9d1d9 prompt: Verify cross-artifact consistency after governance changes
Tc9d1d9---
<!-- Extension: optimize -->
<!-- Config: .specify/extensions/optimize/ -->
Tc9d1d9## User Input
Ta5d6ff```Ta5d6fftext
$ARGUMENTS
Ta5d6ff```
You **MUST** consider the user input before proceeding (if not empty).
Arguments: Ta5d6ff`--category <name>` to run a single category, Ta5d6ff`--report-only` to skip the apply step.
Tc9d1d9## Goal
Audit an existing, populated constitution for problems that are **uniquely harmful in AI-driven development**: token bloat, stale rules, ambiguity causing non-deterministic behavior, redundant governance echoes, and incoherent structure. Produce a findings report with a concrete optimization plan. Apply **only** what the user explicitly approves.
This command does NOT author or amend the constitution (that is Ta5d6ff`/speckit.constitution`). It audits and optimizes existing content.
Tc9d1d9## Operating Constraints
Tff7b72- **Suggest-only**: NEVER modify any file without explicit user consent. Always present findings and a plan first, then ask before applying.
Tff7b72- **Semantic preservation**: Optimization removes redundancy, not intent. Every governance rule must survive compression β only its expression changes.
Tff7b72- **Spec-kit standard paths**: Use Ta5d6ff`.specify/memory/constitution.md` as the primary constitution path. If it contains a redirect (e.g., "Read and follow the constitution in Ta5d6ff`<path>`"), follow the redirect to the actual file. Fallback discovery order: Ta5d6ff`CLAUDE.md`, Ta5d6ff`AGENTS.md`, Ta5d6ff`.github/copilot-instructions.md`.
Tff7b72- **Constitution authority**: Respect the constitution's own governance section. Version bumps follow its defined semver policy.
Tff7b72- **Idempotency**: Running this command twice in succession on an optimized constitution MUST produce no new findings.
Tc9d1d9## Execution Steps
Tc9d1d9### 1. Locate and Load Constitution
Resolution order:
Tff7b721. Read Ta5d6ff`.specify/memory/constitution.md`
Tff7b722. If it contains a redirect pattern (e.g., Ta5d6ff`Read and follow the constitution in <path>`), follow the redirect to the actual file
Tff7b723. If Ta5d6ff`.specify/memory/constitution.md` does not exist, check fallbacks: Ta5d6ff`CLAUDE.md`, Ta5d6ff`AGENTS.md`, Ta5d6ff`.github/copilot-instructions.md`
Tff7b724. Abort with clear error if no constitution found
Validate the file is a populated constitution (not a raw template with Ta5d6ff`[PLACEHOLDER]` tokens). If it is still a template, advise the user to run Ta5d6ff`/speckit.constitution` first and abort.
Record the resolved file path as Ta5d6ff`CONSTITUTION_PATH` for all subsequent steps.
Tc9d1d9### 2. Load Configuration
Check for project config at Ta5d6ff`.specify/extensions/optimize/optimize-config.yml`. If not found, use Ta5d6ff`defaults` from Ta5d6ff`extension.yml`. Parse:
Tff7b72- Which categories are enabled
Tff7b72- Threshold values
Tff7b72- Target context window size
Tc9d1d9### 3. Parse Constitution Structure
Extract and catalog:
Tff7b72- **Sync Impact Report** (HTML comment at top) β version, dates, template status
Tff7b72- **Version History** (HTML comment) β all version entries
Tff7b72- **Title** (H1 heading)
Tff7b72- **Core Principles** β for each: number, name, NON-NEGOTIABLE flag, individual rules as a flat list (each bullet, MUST/SHOULD statement, or table row with normative content)
Tff7b72- **Quality Gates** table
Tff7b72- **Governance** section β authority, amendment process, version semantics
Tff7b72- **Version footer** β current version, ratified date, last amended date
Store each principle's rules as a flat list for cross-comparison.
Tc9d1d9### 4. Discover Governance Ecosystem
Scan for all governance files that AI agents may load:
Tff7b72- Ta5d6ff`.specify/memory/constitution.md` (and its redirect target)
Tff7b72- Ta5d6ff`CLAUDE.md` (root)
Tff7b72- Ta5d6ff`AGENTS.md` (root)
Tff7b72- Ta5d6ff`.github/copilot-instructions.md`
Tff7b72- All files in Ta5d6ff`.ai/rules/` (if directory exists)
Tff7b72- All files in Ta5d6ff`.specify/memory/` (if any beyond constitution)
For each file found, record: path, size in characters, estimated tokens (chars Γ· Ta5d6ff`chars_per_token`).
Tc9d1d9### 5. Run Analysis Categories
Run each enabled category. If Ta5d6ff`--category <name>` was provided, run only that one.
---
Tc9d1d9#### Category 1: Token Budget Analysis
*Why AI-specific*: AI agents pay the full token cost of the constitution on every single invocation. A 3000-token constitution across 50 daily sessions = 150K tokens/day of governance overhead. Humans skim; AI tokenizes everything.
**Checks:**
Tff7b721. **Total token estimate**: Calculate chars Γ· Ta5d6ff`chars_per_token` for the constitution and each governance file discovered in Step 4.
Tff7b722. **Per-section token breakdown**: For each H2/H3 section in the constitution, calculate its token cost and compute a "governance density" score = (number of distinct rules in section) Γ· (estimated tokens in section). Low density = high waste.
Tff7b723. **Version history bloat**: Detect HTML comment blocks containing version history (pattern: Ta5d6ff`<!-- ... v\d+\.\d+\.\d+ ... -->`). These are valuable for humans reviewing the file but add zero governance value for AI agents. Measure their token cost.
Tff7b724. **Anti-pattern tax**: Detect sections containing both "WRONG" / "Anti-Pattern" / "NEVER" code blocks AND "CORRECT" / "RIGHT" / "Correct Pattern" code blocks. The anti-pattern is often inferable from the correct pattern alone. Measure the token cost of each anti-pattern block.
Tff7b725. **Inline code duplication**: For each fenced code block in the constitution, search the repository for matching files or near-matching code. If the code exists in the repo, it can be replaced with a file reference (e.g., "See Ta5d6ff`src/.../BeanConfiguration.java`"). Use glob/grep to find matching class names, method signatures, or patterns from the code block.
Tff7b726. **Double-governance**: For each rule, check if an equivalent enforcement exists in:
Tff7b72- Checkstyle config (glob for Ta5d6ff`**/checkstyle*.xml`)
Tff7b72- Build tool config (glob for Ta5d6ff`build.gradle*`, Ta5d6ff`buildSrc/**`)
Tff7b72- Dependency management (glob for Ta5d6ff`**/libs.versions.toml`, Ta5d6ff`**/pom.xml`)
Tff7b72- CI pipeline config (glob for Ta5d6ff`.github/workflows/*`, Ta5d6ff`.pipelines/*`, Ta5d6ff`azure-pipelines*`)
If a tool already enforces the rule, the constitution copy is redundant β it can be compressed to a reference.
Tff7b727. **Prose-table overlap**: Detect when the same information appears in both prose (paragraph/bullets) and a table within the same H3 section. Measure the overlap token cost.
**Output per finding**: Section path, token cost, issue type, suggested fix, projected savings.
---
Tc9d1d9#### Category 2: Rule Health Analysis
*Why AI-specific*: AI agents have no institutional memory. A rule added 6 months ago for a one-time incident is enforced with the same authority as a core architectural principle. There is no natural "forgetting" mechanism β stale rules persist forever.
**Checks:**
Tff7b721. **Incident-specific rules**: Detect rules that reference specific class names, method names, or file paths (backtick-wrapped identifiers like `` Ta5d6ff`ClassName` ``, `` Ta5d6ff`methodName` ``). Cross-reference: search the codebase for the named artifact. If it exists in only one component or has been removed, the rule may be too narrow for a project-wide constitution or entirely stale.
Tff7b722. **Superseded rules**: Within the same principle and across principles, detect rules that govern the same domain at different specificity levels. Example: "no magic numbers" (general) + "use named constants for all numeric values" (specific) β the specific one supersedes the general.
Tff7b723. **Graduated rules**: For each rule, check if it is fully enforced by automation:
Tff7b72- Parse checkstyle config for matching check names (e.g., Ta5d6ff`MagicNumberCheck` β "no magic numbers" rule)
Tff7b72- Check Ta5d6ff`buildSrc/` for custom Gradle tasks (e.g., Ta5d6ff`CheckFileHeaderTask` β "file headers required")
Tff7b72- Check CI pipeline for quality gates
If a rule is 100% enforced by tooling, the constitution statement is redundant and can be compressed to: "Enforced by [tool] β see Ta5d6ff`[config path]`."
Tff7b724. **Stale rules via git history**: Run Ta5d6ff`git log --follow -p` on the constitution file. For rules introduced in older versions (check the version history comment block), evaluate whether the context that motivated the rule still applies. Flag rules that haven't been touched in >3 versions AND reference specific artifacts.
**Output per finding**: Rule text, principle location, health classification (CORE / OPERATIONAL / INCIDENT-RESPONSE / GRADUATED), recommendation, evidence.
---
Tc9d1d9#### Category 3: AI Interpretability Analysis
*Why AI-specific*: Ambiguity in the constitution causes non-deterministic behavior β different AI sessions resolve the same ambiguity differently, leading to inconsistent codebases. Rules that require human judgment are dead code to AI agents.
**Checks:**
Tff7b721. **Unenforceable rules (require human action)**: Scan for rules containing: "check with", "discuss with", "team lead approval", "manual review", "consult", "ask before", "get sign-off". These are meaningful to humans but unactionable by AI agents.
Tff7b722. **Ambiguous quantifiers**: Scan for rules containing: "appropriate", "reasonable", "sufficient", "proper", "clean", "good", "well-structured", "meaningful", "as needed", "where possible", "when necessary". These are interpreted differently by different AI models and sessions. For each, propose a concrete, deterministic replacement.
Tff7b723. **Missing enforcement mechanism**: For each MUST rule, check if there is a corresponding automated enforcement (checkstyle, CI, Gradle task, spec-kit command). If a rule says MUST but nothing checks compliance, it is "aspirational governance" β effective only when the AI agent happens to remember it.
Tff7b724. **Contradiction detection**: Parse all rules into normalized assertion form. Check for:
Tff7b72- **Direct contradictions**: Rule A says "MUST X" and Rule B says "MUST NOT X" or implies not-X
Tff7b72- **Indirect contradictions**: Rule A requires pattern P, Rule B requires pattern Q, where P and Q are mutually exclusive in practice
Tff7b72- **Scope conflicts**: Two principles claim authority over the same domain with different guidance
For each pair, assess severity: CRITICAL (direct), HIGH (indirect), MEDIUM (scope overlap).
Tff7b725. **Implicit context dependencies**: Scan for rules referencing: "the team's convention", "our usual approach", "as discussed", "you know", "the standard pattern" (without specifying which). These rely on context that AI agents don't carry between sessions.
Tff7b726. **Non-deterministic choice points**: Scan for rules with: "or" / "either...or" / "when appropriate" / "use your judgment" / "consider" that leave the resolution to the AI agent without a default. Each is a source of cross-session inconsistency.
**Output per finding**: Rule text, location, interpretability issue type, proposed deterministic rewrite, severity.
**Per-rule score** (0β100): Based on specificity (25), enforceability (25), determinism (25), self-containedness (25). Report average per principle and overall.
---
Tc9d1d9#### Category 4: Semantic Compression
*Why AI-specific*: 10 verbose rules that could be expressed as 2 concise rules cost 5Γ more context tokens for identical governance. This is not about human readability β it is about information density for context-limited AI consumers.
**Checks:**
Tff7b721. **Collapsible rule clusters**: Group rules by semantic domain (testing, naming, architecture, dependencies, documentation). Within each group, identify rules that share a common parent assertion. Example: "No wildcard imports", "No magic numbers", "Explicit this. prefix", "JavaDoc required" are all checkstyle-enforced quality rules that could be collapsed to a single reference: "All code MUST pass checkstyle (Ta5d6ff`config/checkstyle/checkstyle.xml`) with zero violations." Measure per-cluster token savings.
Tff7b722. **Inline-to-reference conversion**: For each fenced code block (identified in Cat 1), if the code exists as an actual file in the repo, propose replacing the inline block with a file reference. Example: 12 lines of Ta5d6ff`BeanConfiguration` Java code β "See Ta5d6ff`src/.../BeanConfiguration.java` for the canonical pattern." Measure per-block token savings.
Tff7b723. **Redundant examples**: For sections containing both WRONG and CORRECT code blocks, evaluate whether the anti-pattern is inferable from the correct pattern and the rule text. If yes, the anti-pattern block can be removed. Measure savings.
Tff7b724. **Table compression**: Detect tables where most cells follow a derivable pattern. Example: A 7-line Model Types table could be 3 lines of prose. Measure savings.
Tff7b725. **Compressed constitution draft**: If total projected savings exceed 10%, produce a full compressed draft that preserves every governance rule while minimizing tokens. Include a "governance preservation check" listing every original rule and its location in the compressed version.
**Output per finding**: Original section, proposed replacement, token savings, governance preservation confirmation.
---
Tc9d1d9#### Category 5: Constitution Coherence
*Why AI-specific*: AI agents read the constitution linearly and assign roughly equal weight to all sections. A constitution that has grown organically through many amendments tends to be structurally unbalanced β one principle with 30 rules, another with 3. Related rules scattered across principles. Missing cross-references. No clear narrative arc. A human can mentally reorganize; an AI agent cannot.
**Checks:**
Tff7b721. **Principle balance**: Count rules per principle (bullets, MUST/SHOULD statements, normative table rows). Flag if the largest principle has more than Ta5d6ff`principle_balance_ratio` (default: 3Γ) the rules of the smallest. Report the count per principle.
Tff7b722. **Rule scatter**: For each rule, extract its semantic domain (testing, naming, architecture, dependencies, documentation, API, security). If rules from the same domain appear in more than one principle, flag as scattered. Example: naming conventions in Principle I + entity naming in Principle III = naming rules scattered.
Tff7b723. **Missing cross-references**: Detect rules that reference concepts defined in other sections without an explicit cross-reference (e.g., a testing rule mentions "coverage" but coverage thresholds are in Quality Gates β no link between them).
Tff7b724. **Orphaned sections**: Detect sections that are neither referenced by nor reference any other section. These may be bolt-on additions from specific AI sessions that were never integrated into the overall narrative.
Tff7b725. **CLAUDE.md summary drift**: If Ta5d6ff`CLAUDE.md` exists and contains a "Critical Rules" or similar summary section, compare each rule against the constitution. Detect:
Tff7b72- Rules in the summary missing from the constitution (orphaned summaries)
Tff7b72- Rules in the constitution missing from the summary (under-documented)
Tff7b72- Rules with wording differences between the two (drift)
**Output per finding**: Location, issue type, proposed resolution. Overall coherence score (0β100) based on balance (25), scatter (25), cross-referencing (25), drift (25).
---
Tc9d1d9#### Category 6: Governance Echo Detection
*Why AI-specific*: AI-driven projects accumulate multiple governance files β each loaded into the AI context. The same rule restated across files wastes tokens on every invocation and introduces contradiction risk when one copy is updated but others are not.
**Checks:**
Tff7b721. **Cross-file rule duplication**: For each governance file discovered in Step 4, extract rules (bullets, MUST/SHOULD statements, normative table rows). Compare rules across all file pairs. Flag near-duplicates (same semantic intent, different wording).
Tff7b722. **Summary drift**: Compare the main constitution against each governance file that summarizes it (typically Ta5d6ff`CLAUDE.md`). Detect rules updated in one but not the other.
Tff7b723. **Redundant governance files**: If a governance file's rules are entirely a subset of the constitution's rules, the file is redundant. The entire file could be replaced with a pointer: "See Ta5d6ff`.specify/memory/constitution.md`."
Tff7b724. **Governance chain depth**: Trace how the constitution is loaded by each AI tool. Count the number of governance documents in the loading chain and their cumulative token cost.
Tff7b725. **Total governance budget**: Sum estimated tokens across all governance files. Express as a percentage of the target context window (from config). Flag if exceeding Ta5d6ff`governance_budget_percent` (default: 15%).
**Output per finding**: Source file, target file, duplicated rule text, recommendation. Overall governance echo map showing which files duplicate which rules.
---
Tc9d1d9### 6. Generate Unified Findings Report
Combine all category results into a single report. Present to the user:
Ta5d6ff```Ta5d6ffmarkdown
Tc9d1d9## Governance Optimization: Findings Report
**Constitution**: <CONSTITUTION_PATH>
**Current Version**: <version>
**Estimated Tokens**: <total> (~<lines> lines)
**Governance Ecosystem**: <file_count> files, <total_tokens> tokens (<percent>% of <context_window> context)
Tc9d1d9### Executive Summary
| Category | Findings | Severity | Projected Savings |
|----------|----------|----------|-------------------|
| Token Budget | X | <highest> | ~Y tokens |
| Rule Health | X | <highest> | β |
| AI Interpretability | X | <highest> | β |
| Semantic Compression | X | <highest> | ~Y tokens |
| Coherence | X | <highest> | β |
| Governance Echo | X | <highest> | ~Y tokens |
**Overall Health Score**: X/100
**Total Projected Token Reduction**: ~Y tokens (Z%)
Tc9d1d9### Top 5 Findings (by impact)
Tff7b721. [Finding with highest token savings or highest severity]
Tff7b722. ...
Tc9d1d9### Detailed Findings
[Per-category details as described in each category's output section]
Ta5d6ff```
Tc9d1d9### 7. Propose Optimization Plan
Based on findings, produce a concrete plan:
Ta5d6ff```Ta5d6ffmarkdown
Tc9d1d9### Proposed Changes
| # | Change | Category | Files Affected | Token Impact | Risk |
|---|--------|----------|----------------|--------------|------|
| 1 | Remove version history HTML comments | Token Budget | constitution | -X tokens | Low |
| 2 | Compress checkstyle rules to reference | Compression | constitution | -X tokens | Low |
| ... | ... | ... | ... | ... | ... |
Tc9d1d9### Version Bump
Tff7b72- **Type**: PATCH / MINOR / MAJOR
Tff7b72- **Rationale**: [why this bump level]
Tff7b72- **New Version**: X.Y.Z
**Apply these changes?** Select which changes to apply, or approve all.
Ta5d6ff```
Wait for user consent. Do NOT proceed without explicit approval.
Tc9d1d9### 8. Apply Approved Changes
For each user-approved change:
Tff7b721. Apply the modification to Ta5d6ff`CONSTITUTION_PATH`
Tff7b722. Preserve the overall document structure (Sync Impact Report comment, version history, principles, quality gates, governance, footer)
Tff7b723. Update the version footer: bump per the semver rules in the constitution's governance section
Tff7b724. Update Ta5d6ff`Last Amended` date to today (ISO format YYYY-MM-DD)
Tff7b725. Add a new version history entry in the HTML comment block
Tff7b726. Update the Sync Impact Report HTML comment at the top
Tc9d1d9### 9. Post-Application Validation
After writing changes:
Tff7b721. Re-parse the updated constitution β verify no remaining Ta5d6ff`[PLACEHOLDER]` bracket tokens
Tff7b722. Verify version footer matches Sync Impact Report
Tff7b723. Verify all dates are ISO format (YYYY-MM-DD)
Tff7b724. Re-run a quick check on the output β verify no new contradictions or ambiguities were introduced by the edits
Tff7b725. Verify the total governance rule count has not decreased (compression changes expression, not intent)
Tc9d1d9### 10. Output Summary
Ta5d6ff```Ta5d6ffmarkdown
Tc9d1d9## Governance Optimization Complete
**Version**: <old> β <new> (<bump-type>)
**Constitution**: <CONSTITUTION_PATH>
**Token Reduction**: <old_tokens> β <new_tokens> (<percent>% savings)
Tc9d1d9### Changes Applied
Tff7b72- [List of applied changes with token impact]
Tc9d1d9### Changes Declined
Tff7b72- [List of user-declined changes, preserved for next run]
Tc9d1d9### Sync Impact Report Updated
Tff7b72- Version change: <old> β <new>
Tff7b72- Modified sections: [list]
Tff7b72- Templates status: [all aligned / needs review]
Tc9d1d9### Suggested Commit Message
docs: optimize constitution to v<new> β reduce governance token overhead by <percent>%
Tc9d1d9### Recommended Follow-Up
Tff7b72- Review updated constitution for accuracy
Tff7b72- Run Ta5d6ff`/speckit.constitution` if substantive amendments are needed beyond optimization
Tff7b72- Run Ta5d6ff`/speckit.analyze` to verify cross-artifact consistency
Tff7b72- Run Ta5d6ff`/speckit.optimize.tokens` to verify ecosystem-wide token budget
Ta5d6ff```
Tc9d1d9## Operating Principles
Tc9d1d9### Suggest-Only
Every change is proposed, never applied silently. The user has full veto power over every individual finding. "Apply all" is offered as a convenience but never the default.
Tc9d1d9### Semantic Preservation
Optimization MUST NOT change the meaning of any rule. Compression removes redundancy in expression, not in intent. After optimization, every governance rule that existed before MUST still be expressible from the optimized document.
Tc9d1d9### Constitution Authority
The review respects the constitution's own governance section. Version bumps follow the defined semver policy. If the governance section specifies an amendment process, the optimization follows it.
Tc9d1d9### Idempotency
Running this command twice in succession on the same constitution MUST produce zero new findings on the second run. If it does not, there is a bug in the optimization logic.
Tc9d1d9### Context Efficiency
The primary goal is making the constitution cheaper to include in AI context windows while maintaining full governance clarity. Every recommendation must be justified by a concrete token savings figure or a measurable improvement in AI interpretability.
Served by rngit 1.5.2 - Generated in 0.12s